// pages/search/index.js
var util = require('../../utils/util.js');
Component({
  data: {
    expertList: [],
    routeList: [],
    screenShow: false,
    list: ['出发', '目的地'],
    result: '出发',
    screenName: '',
    abroadList: {
      province_list: {
        110000: '北京市',
        120000: '天津市'
      },
      city_list: {
        110100: '北京市',
        110200: '县',
        120100: '天津市',
        120200: '县'
      },
      county_list: {
        110101: '东城区',
        110102: '西城区',
        110105: '朝阳区',
        110106: '丰台区',
        120101: '和平区',
        120102: '河东区',
        120103: '河西区',
        120104: '南开区',
        120105: '河北区',
      }
    },
    domesticList: {
      province_list: {
        110000: '北京市',
        120000: '天津市'
      },
      city_list: {
        110100: '北京市',
        110200: '县',
        120100: '天津市',
        120200: '县'
      },
      county_list: {
        110101: '东城区',
        110102: '西城区',
        110105: '朝阳区',
        110106: '丰台区',
        120101: '和平区',
        120102: '河东区',
        120103: '河西区',
        120104: '南开区',
        120105: '河北区',
      }
    },
    abroadAddr: '国家-地区',
    inlandAddr: '省-市',
    screenTypeList: ['文化游', '购物游', '工业游'],
    screenType: 0,
    leftMonth: '1月',
    rightMonth: '12月',
    leftDay: '1天',
    rightDay: '30天',
    offset: 0,
    limit: 10,
    keyShow: false,
    selectMonth: '请选择月份',//开始的月份
    selectOver:'请选择月份',
    tiemselect: false,
    //天数
    selectDay:'请选择天数',
    selectDayOver:'请选择天数',

    //月份
 
    array: ['1', '2', '3', '4','5','6','7','8','9','10','11','12'],
    arrays: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13','14','15','16','17','18','19']
  },
  properties: {},
  methods: {
// 选择月份开始
    bindPickerChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      console.log(this.data.array)
      var index = e.detail.value
      var b = this.data.array[index]
      console.log(b)
      this.setData({
        selectMonth: b+'月'
       
      })
      // 开始月份
      this.data.selectMonth = b
    },
    //
    bindPickerChangeOver:function(e){
      console.log('picker发送选择改变，携带值为', e.detail.value)
      console.log(this.data.array)
      var index = e.detail.value
      var b = this.data.array[index]
      console.log(b)
      this.setData({
        selectOver: b + '月'

      })
      // 结束月份
      console.log(1234)
      this.data.selectOver=b
      console.log(this.data.selectOver)
    },

    // 天数开始
    bindPickerChangeDays:function(e){
      console.log('picker发送选择改变，携带值为', e.detail.value)
      console.log(this.data.arrays)
      var index = e.detail.value
      var b = this.data.arrays[index]
      console.log(b)
      this.setData({
        selectDay: b + '天'

      })
      // 开始的天数
      this.data.selectDay = b
    },
 
    bindPickerChangeOverDay:function(e){
      console.log('picker发送选择改变，携带值为', e.detail.value)
      console.log(this.data.arrays)
      var index = e.detail.value
      var b = this.data.arrays[index]
      console.log(b)
      this.setData({
        selectDayOver: b + '天'

      })
      // 结束的天数
      this.data.selectDayOver = b
    },
  // 天数结束

    // 
    onInput(event) {
      this.setData({
        currentDate: event.detail
      });
    },
    initPartner(arr, size) {
      // 遍历获取
      var oddArr = []; // 奇数数组
      var evenArr = []; // 偶数数组
      for (let i = 0; i < arr.length; i++) {
        // 偶数下标

        if (i % 2 == 0) {
          oddArr.push(arr[i])
        } else {
          // 奇数下标
          evenArr.push(arr[i])
        }
      }
      let _arr = [oddArr, evenArr]

      return _arr
    },
    screenShow() {
      let that = this;
      this.setData({
        screenShow: true
      })
      // that.selectComponent('#monthSlider').show();
      // that.selectComponent('#daySlider').show();
    },
    screenHide() {
      this.setData({
        screenShow: false
      })
    },
    abroadShow() {
      this.setData({
        abroadShow: true
      })
    },
    abroadHide() {
      this.setData({
        abroadShow: false,
        tiemselect: false
      })
    },
    domesticShow() {
      this.setData({
        domesticShow: true
      })
    },
    domesticHide() {
      this.setData({
        domesticShow: false
      })
    },
    // 时间选择事件
    tiemselect() {
      // this.setData({
      //   tiemselect: true
      // })
      wx.showActionSheet({

        itemList: ['1', '2', '3'],
        success: function (res) {
          if (!res.cancel) {
            console.log(res.tapIndex)//这里是点击了那个按钮的下标
            console.log(123)
        
          }
        
        }
      })
    },

    //确认事件
    abroadConfirm(e) {
      this.abroadHide();
      console.log(e.detail.values);
      let values = e.detail.values.map(item => item && item.name);
      values = values.filter(item => item && item.length > 0);
      this.setData({
        abroadAddr: values[values.length - 1],
        inlandAddr: '省-市'
      });
      this.data.abroadAddr = values.join('-');
    },
    domesticConfirm(e) {
      this.domesticHide();
      console.log(e.detail.values);
      let values = e.detail.values.map(item => item && item.name);
      values = values.filter(item => item && item.length > 0);
      this.setData({
        inlandAddr: values[values.length - 1],
        abroadAddr: '国家-地区'
      });
      this.data.inlandAddr = values.join('-');
    },

    addChange(event) {
      console.log(event)
      this.setData({
        result: event.detail
      });
    },
    leftMonthChange(e) {
      console.log(122)

      this.setData({
        leftMonth: e.detail.lowValue + '月'
      })
      this.data.leftMonth = e.detail.lowValue;
      console.log(this.data.leftMonth)
    },
    rightMonthChange(e) {
      this.setData({
        rightMonth: e.detail.heighValue + '月'
      })
      this.data.rightMonth = e.detail.heighValue;
      console.log(this.data.rightMonth)
    },
    leftDayChange(e) {
      this.setData({
        leftDay: e.detail.lowValue + '天'
      })
      this.data.leftDay = e.detail.lowValue;
    },
    rightDayChange(e) {
      this.setData({
        rightDay: e.detail.heighValue + '天'
      })
      this.data.rightDay = e.detail.heighValue;
    },
    choseType(e) {
      this.setData({
        screenType: e.currentTarget.dataset.index,
        screenName: e.currentTarget.dataset.name
      })
    },

    //重置搜索条件
    resetSearch() {
      this.setData({
        result: '出发',
        abroadAddr: '国家-地区',
        inlandAddr: '省-市',
        screenType: 0,
        selectMonth: '请选择月份',//开始的月份
        selectOver: '请选择月份',
        selectDay: '请选择天数',
        selectDayOver: '请选择天数'
      });
    },

    //发出搜索请求
    goSearch() {
      console.log(this.data.leftMonth)
      let that = this;
      let is_abroad = 1;
      let reqData = {
        offset: this.data.offset,
        limit: this.data.limit,
        is_abroad: 1, //	1国内 2国外  this.data.selectMonth
        // start_month: this.data.leftMonth,
        start_month: this.data.selectMonth,
        // end_month: this.data.rightMonth,
        end_month: this.data.selectOver,

        // start_day: this.data.leftDay,
        start_day: this.data.selectDay,
        end_day: this.data.selectDayOver,
        classify_id: this.data.screenTypeList[this.data.screenType].classify_id
      };
      console.log(this.data.result);
      if (this.data.abroadAddr != '国家-地区') {
        reqData.is_abroad = 2;
      }
      let addr = [];
      if (reqData.is_abroad == 1 && this.data.inlandAddr != '省-市') { //国内
        addr = ['中国'].concat(this.data.inlandAddr.split("-"));
      } else if (reqData.is_abroad == 2 && this.data.abroadAddr != '国家-地区') { //国外
        addr = this.data.abroadAddr.split("-");
      }
      if (this.data.result.indexOf('出发') >= 0) {
        reqData.start_province = addr.length > 1 ? addr[1] : '';
        reqData.start_city = addr.length > 2 ? addr[2] : '';
      }
      if (this.data.result.indexOf('目的地') >= 0) {
        reqData.end_country = addr.length > 0 ? addr[0] : '';
        reqData.end_province = addr.length > 1 ? addr[1] : '';
        reqData.end_city = addr.length > 2 ? addr[2] : '';
      }
      console.log("--------request data");
      console.log(reqData);

      util.http({
        url: '/api/miniwechat/index/search',
        method: 'POST',
        data: reqData
      }).then(res => {
        console.log("-------------👇");
        console.log(res);
        if (!res.line.rows) {
          wx.showToast({
            title: '查无数据',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        wx.setStorage({
          key: "searchData",
          data: reqData
        })
        res.line.rows.forEach((item, index) => {
          if (!item.line_time_list || item.line_time_list.length == 0) {
            return;
          }
          let beginTime = item.line_time_list.begin_time
          let endTime = item.line_time_list.end_time
          console.log(beginTime)
          console.log(endTime)
          let totalTime = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1 * 24 * 60 * 60 * 1000)
          let surplusNum = item.line_time_list.quota - item.line_time_list.number
          item.line_time_list.totalTime = totalTime
          item.line_time_list.begin_time = timeReset(beginTime)
          item.line_time_list.end_time = timeReset(endTime)
          item.line_time_list.surplusNum = surplusNum
          switch (item.line_time_list.status) {
            case 0:
              item.line_time_list.state = '已取消'
              break;
            case 1:
              item.line_time_list.state = '报名中'
              break;
            case 2:
              item.line_time_list.state = '报名结束'
              break;
            case 3:
              item.line_time_list.state = '已完成'
              break;
          }
        })
        //渲染搜索结果↓↓↓↓↓↓↓↓↓↓↓↓↓
        that.setData({
          routeList: this.initPartner(res.line.rows, 2),
          expertList: res.guide.rows,
          screenShow: false,
          keyShow: true
        })
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    },

    getSearch() {
      let that = this;
      util.http({
        url: '/api/miniwechat/index/search'
      }).then(res => {
        console.log("-------------👇");
        console.log(res);
        //渲染搜索结果↓↓↓↓↓↓↓↓↓↓↓↓↓
        res.line.rows.forEach((item, index) => {
          if (!item.line_time_list || item.line_time_list.length == 0) {
            return;
          }
          let beginTime = item.line_time_list.begin_time
          let endTime = item.line_time_list.end_time
          let totalTime = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1 * 24 * 60 * 60 * 1000)
          let surplusNum = item.line_time_list.quota - item.line_time_list.number
          item.line_time_list.totalTime = totalTime
          item.line_time_list.begin_time = timeReset(beginTime)
          item.line_time_list.end_time = timeReset(endTime)
          item.line_time_list.surplusNum = surplusNum
          switch (item.line_time_list.status) {
            case 0:
              item.line_time_list.state = '已取消'
              break;
            case 1:
              item.line_time_list.state = '报名中'
              break;
            case 2:
              item.line_time_list.state = '报名结束'
              break;
            case 3:
              item.line_time_list.state = '已完成'
              break;
          }
        })
        that.setData({
          routeList: this.initPartner(res.line.rows, 2),
          expertList: res.guide.rows
        })
        console.log(this.data.routeList)
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    },

    goRouteDetail(e) {
      wx.navigateTo({
        url: '/pages/routeDetail/index?id=' + e.currentTarget.dataset.id,
      })
    },
    goExpertDetail(e) {
      wx.navigateTo({
        url: '/pages/expertDetail/index?id=' + e.currentTarget.dataset.id
      })
    },

    goExpertMore() {
      wx.navigateTo({
        url: '/pages/expertList/index'
      })
    },
    goRouteListMore() {
      wx.navigateTo({
        url: '/pages/routeList/index'
      })
    },

    //获取线路主题分类
    getLineClassify() {
      let that = this;
      util.http({
        url: '/api/miniwechat/index/line_classify',
      }).then(res => {
        console.log("--------------getLineClassify");
        console.log(res);
        that.setData({
          screenTypeList: res
        });
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    },

    //格式化国内地址
    formatAddr(addrData) {
      let inland = addrData[0];
      var inlandProv = {};
      var inlandCity = {};
      var inlandCounty = {};
      var code = 10;
      for (let i = 0, j = inland.s.length; i < j; ++i) {
        code++;
        let prov = inland.s[i];
        let provCode = code * 10000;
        inlandProv[provCode] = prov.n;
        let provCity = prov.s;
        if (!provCity[0].s) { //直辖市下没有市
          provCity = prov;
          let cityCode = provCode + 100;
          inlandCity[cityCode] = provCity.n;
          let cityCounty = provCity.s;
          for (let p = 0, q = cityCounty.length; p < q; ++p) {
            let countyCode = cityCode + p + 1;
            let county = cityCounty[p];
            inlandCounty[countyCode] = county.n;
          }
          continue;
        }
        for (let l = 0, m = provCity.length; l < m; ++l) {
          let cityCode = provCode + (l + 1) * 100;
          let city = provCity[l];
          inlandCity[cityCode] = city.n;
          let cityCounty = city.s;
          if (!cityCounty) { //一些市下面，没有县
            // console.log(city);
            continue;
          }
          for (let p = 0, q = cityCounty.length; p < q; ++p) {
            let countyCode = cityCode + p + 1;
            let county = cityCounty[p];
            inlandCounty[countyCode] = county.n;
          }
        }
      }

      this.setData({
        domesticList: {
          province_list: inlandProv,
          city_list: inlandCity,
          county_list: inlandCounty
        }
      });
    },

    //格式化国外地址
    formatAbroadAddr(addrData) {
      let abroad = addrData.slice(1);
      var abroadProv = {};
      var abroadCity = {};
      var abroadCounty = {};
      var code = 10;
      for (let i = 0, j = abroad.length; i < j; ++i) {
        code++;
        let prov = abroad[i];
        let provCode = code * 10000;
        abroadProv[provCode] = prov.n;
        let provCity = prov.s;
        if (!provCity) { //一些国家下面没有具体地区
          // console.log("没有具体地区");
          // console.log(prov);
          continue;
        }
        for (let l = 0, m = provCity.length; l < m; ++l) {
          let cityCode = provCode + (l + 1) * 100;
          let city = provCity[l];
          abroadCity[cityCode] = city.n;
          let cityCounty = city.s;
          if (!cityCounty) { //一些市下面，没有县
            continue;
          }

          for (let p = 0, q = cityCounty.length; p < q; ++p) {
            let countyCode = cityCode + p + 1;
            let county = cityCounty[p];
            abroadCounty[countyCode] = county.n;
          }
        }
      }

      this.setData({
        abroadList: {
          province_list: abroadProv,
          city_list: abroadCity,
          county_list: abroadCounty
        }
      });
    },

    //获取地址json，要用wx.request
    getAddrJson() {
      let that = this;
      let wxReq = util.wxPromisify(wx.request);
      wxReq({
        url: util.host + '/assets/libs/fastadmin-cxselect/js/globalData.min.json'
      }).then(res => {
        console.log("--------------getAddrJson");
        console.log(res.data);
        that.formatAddr(res.data);

        that.formatAbroadAddr(res.data);

      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    },
    goMore(e) {
      wx.navigateTo({
        url: '/pages/searchMore/index?index=' + e.currentTarget.dataset.index,
      })
    }
  },
  ready: function (options) {
    wx.removeStorageSync('searchData')
    this.data.leftMonth = '1';
    this.data.rightMonth = '12';
    this.data.leftDay = '1';
    this.data.rightDay = '15';
    util.http({
      url: 'api/miniwechat/index/search',
      method: 'GET'
    }).then(res => { }).catch(err => {
      console.log(err);
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })

  },
  attached() {
    console.log(this.data.routeList);
    this.getLineClassify();
    this.getAddrJson();
    this.getSearch();
  }
})

function timeReset(time) {
  let arr = time.split("-")
  arr.splice(0, 1)
  arr = arr.join(".")
  return arr
}